<template>
  <div class="app-container">
    <div class="content-wrapper">
      <!-- 面试安排表格 -->
      <div class="schedule-table-wrapper">
        <div class="table-header">
          <div class="header-left">
            <h1>面试安排</h1>
            <p>查看并管理所有面试安排</p>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="handleAddSchedule" class="add-btn">
              <el-icon><Plus /></el-icon>
              安排新面试
            </el-button>
          </div>
        </div>

        <div class="table-container">
          <el-table 
            :data="tableData" 
            style="width: 100%" 
            v-loading="loading"
            border
            @row-click="viewRecord"
            :header-cell-style="{
              background: '#f5f7fa',
              color: '#1f2f3d',
              fontWeight: '600',
              height: '56px'
            }"
          >
            <el-table-column label="候选人" min-width="180" class="candidate-column">
              <template #default="scope">
                <div class="candidate-info">
                  <div class="avatar" :style="{ backgroundColor: getAvatarColor(getCandidateName(scope.row.candidateId)) }">
                    {{ getInitials(getCandidateName(scope.row.candidateId)) }}
                  </div>
                  <span class="candidate-name">{{ getCandidateName(scope.row.candidateId) }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="positionId" label="职位" min-width="150" class="position-column">
              <template #default="scope">
                {{ getPositionName(scope.row.positionId) }}
              </template>
            </el-table-column>
            <el-table-column prop="digitalInterviewerId" label="面试官" min-width="150" class="interviewer-column">
              <template #default="scope">
                <div class="interviewer-info">
                  <el-icon><User /></el-icon>
                  <span>{{ getInterviewerName(scope.row.digitalInterviewerId) }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="interviewDate" label="面试日期" min-width="120" class="date-column">
              <template #default="scope">
                <div class="date-info">
                  <el-icon><Calendar /></el-icon>
                  <span>{{ formatDate(scope.row.interviewDate) || '未设置' }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="interviewTime" label="面试时间" min-width="120" class="time-column">
              <template #default="scope">
                <div class="time-info">
                  <el-icon><Timer /></el-icon>
                  <span>{{ scope.row.interviewTime || '未设置' }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="duration" label="时长" min-width="100" class="duration-column">
              <template #default="scope">
                <div class="duration-info">
                  <el-icon><Timer /></el-icon>
                  <span>{{ scope.row.duration || 0 }}分钟</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" min-width="100" class="status-column">
              <template #default="scope">
                <el-tag
                  :type="getStatusType(scope.row.candidateId)"
                  effect="light"
                  size="large"
                  class="status-tag"
                >
                  {{ getStatusText(scope.row.candidateId) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="notes" label="备注" min-width="200" class="remarks-column">
              <template #default="scope">
                <div class="remarks-content">
                  {{ scope.row.notes || '暂无备注' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="questionSetIds" label="题目集" min-width="200" class="question-set-column">
              <template #default="scope">
                <div class="question-set-info">
                  <el-icon><Document /></el-icon>
                  <span>{{ getQuestionSetNames(scope.row.questionSetIds) }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="280" fixed="right" class="operation-column">
              <template #default="scope">
                <div class="operation-buttons">
                  <el-button 
                    type="primary" 
                    link
                    @click.stop="viewRecord(scope.row)"
                    class="action-btn"
                  >
                    <el-icon><View /></el-icon>
                    <span>查看</span>
                  </el-button>
                  <el-button 
                    type="primary" 
                    link
                    @click.stop="handleEdit(scope.row)"
                    class="action-btn"
                  >
                    <el-icon><Edit /></el-icon>
                    <span>编辑</span>
                  </el-button>
                  <el-button 
                    type="danger" 
                    link
                    @click.stop="cancelInterview(scope.row.id)"
                    class="action-btn"
                  >
                    <el-icon><Close /></el-icon>
                    <span>取消</span>
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <div class="pagination-info">
            显示 {{ startIndex }} 到 {{ endIndex }}，共 {{ total }} 条记录
          </div>
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :current-page="currentPage"
            :page-size="pageSize"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>

    <!-- 添加/编辑面试安排对话框 -->
    <el-dialog
      :title="form.id ? '编辑面试安排' : '安排新面试'"
      v-model="dialogVisible"
      width="50%"
      :before-close="handleClose"
      destroy-on-close
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="schedule-form">
        <el-form-item label="候选人" prop="candidateId">
          <el-select v-model="form.candidateId" placeholder="请选择候选人" @change="handleCandidateChange">
            <el-option v-for="candidate in candidates" :key="candidate.id" :label="candidate.name" :value="candidate.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="职位" prop="positionId">
          <el-select v-model="form.positionId" placeholder="请选择职位" @change="handlePositionChange">
            <el-option 
              v-for="position in positions" 
              :key="position.id" 
              :label="position.name || position.positionName" 
              :value="position.id || position.positionId" 
            />
          </el-select>
        </el-form-item>

        <el-form-item label="面试类型" prop="interviewType">
          <el-select v-model="form.interviewType" placeholder="请选择面试类型">
            <el-option label="数字人面试" :value="1" />
            <el-option label="人工面试" :value="2" />
            <el-option label="混合面试" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="面试官" prop="digitalInterviewerId">
          <el-select v-model="form.digitalInterviewerId" placeholder="请选择面试官" @change="handleInterviewerChange">
            <el-option v-for="interviewer in interviewers" :key="interviewer.id" :label="interviewer.name" :value="interviewer.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="面试日期" prop="interviewDate">
          <el-date-picker
            v-model="form.interviewDate"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>

        <el-form-item label="面试时间" prop="interviewTime">
          <el-time-picker
            v-model="form.interviewTime"
            placeholder="选择时间"
            format="HH:mm"
            value-format="HH:mm"
          />
        </el-form-item>

        <el-form-item label="时长" prop="duration">
          <el-input-number 
            v-model="form.duration" 
            :min="15" 
            :max="180"
            placeholder="请输入面试时长（分钟）"
          />
        </el-form-item>

        <el-form-item label="发送邮件" prop="sendEmail">
          <el-select v-model="form.sendEmail" placeholder="请选择是否发送邮件">
            <el-option label="否" :value="0" />
            <el-option label="是" :value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="题目集" prop="questionSetIds">
          <el-select
            v-model="form.questionSetIds"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择题目集"
          >
            <el-option
              v-for="set in questionSets"
              :key="set.id"
              :label="set.name"
              :value="set.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            type="textarea"
            v-model="form.notes"
            placeholder="请输入备注信息..."
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">{{ form.id ? '保存' : '安排面试' }}</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 面试详情对话框 -->
    <el-dialog
      title="面试详情"
      v-model="detailDialogVisible"
      width="70%"
      destroy-on-close
    >
      <div v-loading="loadingDetail" class="schedule-detail">
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="候选人">
              {{ getCandidateName(currentRecord?.candidateId) }}
            </el-descriptions-item>
            <el-descriptions-item label="职位">
              {{ getPositionName(currentRecord?.positionId) }}
            </el-descriptions-item>
            <el-descriptions-item label="面试官">
              {{ getInterviewerName(currentRecord?.digitalInterviewerId) }}
            </el-descriptions-item>
            <el-descriptions-item label="面试日期">
              {{ formatDate(currentRecord?.interviewDate) }}
            </el-descriptions-item>
            <el-descriptions-item label="面试时间">
              {{ formatTime(currentRecord?.interviewTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="面试时长">
              {{ currentRecord?.duration }}分钟
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(currentRecord?.candidateId)">
                {{ getStatusText(currentRecord?.candidateId) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="备注">
              {{ currentRecord?.notes || '暂无备注' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 题目集信息 -->
        <div class="detail-section" v-if="currentRecord?.questionSetIds && currentRecord.questionSetIds.length > 0">
          <h3>题目集</h3>
          <el-table :data="getQuestionSetDetails(currentRecord.questionSetIds)" border style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="题目集名称" />
            <el-table-column prop="questionCount" label="题目数量" width="100" />
            <el-table-column prop="orderNum" label="排序" width="80" />
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, View, User, Calendar, Timer, Location, Close, Document } from '@element-plus/icons-vue'
import {
  getScheduleList,
  addSchedule,
  updateSchedule,
  deleteSchedule,
  getScheduleById
} from '@/api/interviewScheduleApi'

import {
  getCandidateList,
  getPositionList,
  getInterviewerList,
  getQuestionSetList
} from '@/api/commonApi'

// 数据相关
const tableData = ref([])
const loading = ref(false)
const loadingDetail = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const formRef = ref(null)
const currentRecord = ref(null)

// 下拉选项数据
const candidates = ref([])
const positions = ref([])
const interviewers = ref([])
const questionSets = ref([])

// 状态映射
const statusMap = {
  '未开始': 1,
  '面试中': 2,
  '面试完成': 3
}

const statusReverseMap = {
  1: '未开始',
  2: '面试中',
  3: '面试完成'
}

// 面试类型映射
const interviewTypeMap = {
  '数字人面试': 1,
  '人工面试': 2,
  '混合面试': 3
}

const interviewTypeReverseMap = {
  1: '数字人面试',
  2: '人工面试',
  3: '混合面试'
}

// 表单数据
const form = reactive({
  id: null,
  candidateId: null,
  positionId: null,
  interviewType: 1,
  interviewDate: '',
  interviewTime: '',
  duration: 60,
  digitalInterviewerId: null,
  notes: '',
  sendEmail: 0,
  questionSetIds: null
})

// 表单验证规则
const rules = {
  candidateId: [{ required: true, message: '请选择候选人', trigger: 'change' }],
  positionId: [{ required: true, message: '请选择职位', trigger: 'change' }],
  interviewType: [{ required: true, message: '请选择面试类型', trigger: 'change' }],
  interviewDate: [{ required: true, message: '请选择面试日期', trigger: 'change' }],
  interviewTime: [{ required: true, message: '请选择面试时间', trigger: 'change' }],
  duration: [
    { required: true, message: '请设置面试时长', trigger: 'blur' },
    { type: 'number', min: 15, max: 180, message: '面试时长必须在15-180分钟之间', trigger: 'blur' }
  ]
}

// 获取面试安排列表
const fetchSchedules = async () => {
  loading.value = true
  try {
    const response = await getScheduleList({
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    if (response.code === 200) {
      // 字段适配：remarks/notes统一为notes，interviewDate/interviewTime分离
      tableData.value = (response.data.list || []).map(item => ({
        ...item,
        notes: item.notes || item.remarks || '',
        interviewDate: item.interviewDate || (item.interviewTime ? new Date(item.interviewTime).toISOString().split('T')[0] : ''),
        interviewTime: item.interviewTime ? (typeof item.interviewTime === 'string' && item.interviewTime.length > 10 ? item.interviewTime : '') : ''
      }))
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '获取面试安排失败')
    }
  } catch (error) {
    ElMessage.error('获取面试安排失败')
  } finally {
    loading.value = false
  }
}

// 计算分页信息
const startIndex = computed(() => {
  return (currentPage.value - 1) * pageSize.value + 1
})

const endIndex = computed(() => {
  return Math.min(currentPage.value * pageSize.value, total.value)
})

// 获取头像颜色
const getAvatarColor = (name) => {
  if (!name) return '#909399'
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
  let hash = 0
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash)
  }
  return colors[Math.abs(hash) % colors.length]
}

// 获取姓名缩写
const getInitials = (name) => {
  if (!name) return '?'
  return name.charAt(0).toUpperCase()
}

// 获取状态类型
const getStatusType = (status) => {
  if (!status) return 'info'
  
  // 从候选人数据中获取状态
  const candidate = candidates.value.find(c => c.id === status)
  if (!candidate) return 'info'
  
  // 根据候选人面试状态返回对应的类型
  const typeMap = {
    1: 'info',      // 未开始
    2: 'warning',   // 面试中
    3: 'success'    // 面试完成
  }
  return typeMap[Number(candidate.interviewStatus)] || 'info'
}

// 获取状态显示文本
const getStatusText = (status) => {
  if (!status) return '未知'
  
  // 从候选人数据中获取状态
  const candidate = candidates.value.find(c => c.id === status)
  if (!candidate) return '未知'
  
  // 状态映射
  const statusMap = {
    1: '未开始',
    2: '面试中',
    3: '面试完成'
  }
  
  return statusMap[Number(candidate.interviewStatus)] || '未知'
}

// 获取下拉选项数据
const fetchOptions = async () => {
  try {
    // 获取候选人列表
    const candidatesRes = await getCandidateList()
    if (candidatesRes.code === 200 && candidatesRes.data) {
      candidates.value = Array.isArray(candidatesRes.data) ? candidatesRes.data : 
                        (candidatesRes.data.records || [])
      // 确保ID是数字类型
      candidates.value = candidates.value.map(c => ({
        ...c,
        id: Number(c.id)
      }))
    }
    
    // 获取职位列表
    const positionsRes = await getPositionList()
    if (positionsRes.code === 200 && positionsRes.data) {
      positions.value = Array.isArray(positionsRes.data) ? positionsRes.data : 
                       (positionsRes.data.records || [])
      // 确保ID是数字类型
      positions.value = positions.value.map(p => ({
        ...p,
        id: Number(p.id || p.positionId)
      }))
    }
    
    // 获取面试官列表
    const interviewersRes = await getInterviewerList()
    if (interviewersRes.code === 200 && interviewersRes.data) {
      interviewers.value = Array.isArray(interviewersRes.data) ? interviewersRes.data : 
                          (interviewersRes.data.records || [])
      // 确保ID是数字类型
      interviewers.value = interviewers.value.map(i => ({
        ...i,
        id: Number(i.id)
      }))
    }
    
    // 获取题目集列表
    const questionSetRes = await getQuestionSetList()
    
    if (questionSetRes.code === 200) {
      if (Array.isArray(questionSetRes.data)) {
        questionSets.value = questionSetRes.data.map(q => ({
          id: Number(q.id),
          name: q.name || '未命名题目集',
          questionCount: q.questionCount || 0,
          orderNum: q.orderNum || 0
        }))
      } else if (questionSetRes.data && questionSetRes.data.records) {
        questionSets.value = questionSetRes.data.records.map(q => ({
          id: Number(q.id),
          name: q.name || '未命名题目集',
          questionCount: q.questionCount || 0,
          orderNum: q.orderNum || 0
        }))
      } else {
        // 临时使用模拟数据
        questionSets.value = [
          { id: 1, name: 'Java基础题目集', questionCount: 20, orderNum: 1 },
          { id: 2, name: 'Spring框架题目集', questionCount: 15, orderNum: 2 },
          { id: 3, name: '数据库题目集', questionCount: 25, orderNum: 3 },
          { id: 4, name: '算法题目集', questionCount: 30, orderNum: 4 },
          { id: 5, name: '系统设计题目集', questionCount: 10, orderNum: 5 }
        ]
      }
    } else {
      // 临时使用模拟数据
      questionSets.value = [
        { id: 1, name: 'Java基础题目集', questionCount: 20, orderNum: 1 },
        { id: 2, name: 'Spring框架题目集', questionCount: 15, orderNum: 2 },
        { id: 3, name: '数据库题目集', questionCount: 25, orderNum: 3 },
        { id: 4, name: '算法题目集', questionCount: 30, orderNum: 4 },
        { id: 5, name: '系统设计题目集', questionCount: 10, orderNum: 5 }
      ]
      ElMessage.warning('使用模拟数据，实际数据获取失败')
    }
  } catch (error) {
    console.error('获取选项数据错误:', error)
    ElMessage.error('获取数据失败')
  }
}

// 候选人变更处理
const handleCandidateChange = (value) => {
  const candidate = candidates.value.find(c => c.id === value)
  if (candidate) {
    form.candidateName = candidate.name
  }
}

// 职位变更处理
const handlePositionChange = (value) => {
  const position = positions.value.find(p => String(p.id || p.positionId) === String(value))
  if (position) {
    form.position = position.name || position.positionName
  }
}

// 面试官变更处理
const handleInterviewerChange = (value) => {
  const interviewer = interviewers.value.find(i => i.id === value)
  if (interviewer) {
    form.interviewer = interviewer.name
  }
}

// 初始化表单数据
const initFormData = () => {
  form.id = null
  form.candidateId = null
  form.positionId = null
  form.interviewType = 1
  form.interviewDate = ''
  form.interviewTime = ''
  form.duration = 60
  form.digitalInterviewerId = null
  form.notes = ''
  form.sendEmail = 0
  form.questionSetIds = []
}

// 新增面试安排
const handleAddSchedule = () => {
  initFormData()
  dialogVisible.value = true
}

// 编辑面试安排
const handleEdit = async (row) => {
  try {
    await fetchOptions()
    
    // 解析日期和时间
    let interviewDate = null
    let interviewTime = null
    if (row.interviewTime) {
      try {
        const date = new Date(row.interviewTime)
        if (!isNaN(date.getTime())) {
          // 格式化日期为 YYYY-MM-DD
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          interviewDate = `${year}-${month}-${day}`
          
          // 格式化时间为 HH:mm
          const hours = String(date.getHours()).padStart(2, '0')
          const minutes = String(date.getMinutes()).padStart(2, '0')
          interviewTime = `${hours}:${minutes}`
        }
      } catch (e) {
        console.error('解析时间失败:', e)
      }
    }
    
    // 设置表单数据
    Object.assign(form, {
      id: row.id,
      candidateId: Number(row.candidateId),
      positionId: Number(row.positionId),
      interviewType: Number(row.interviewType) || 1,
      interviewDate: interviewDate,
      interviewTime: interviewTime,
      duration: Number(row.duration) || 60,
      digitalInterviewerId: row.digitalInterviewerId ? Number(row.digitalInterviewerId) : null,
      notes: row.notes || '',
      sendEmail: Number(row.sendEmail) || 0,
      questionSetIds: Array.isArray(row.questionSetIds) ? row.questionSetIds.map(id => Number(id)) : []
    })
    
    dialogVisible.value = true
  } catch (error) {
    console.error('加载编辑数据失败:', error)
    ElMessage.error('加载编辑数据失败')
  }
}

// 查看面试详情
const viewRecord = async (row) => {
  try {
    loadingDetail.value = true
    currentRecord.value = row
    
    // 获取面试详情
    const detailResponse = await getScheduleById(row.id)
    
    if (detailResponse.code === 200) {
      currentRecord.value = { ...row, ...detailResponse.data }
    } else {
      ElMessage.error(detailResponse.msg || '获取面试详情失败')
    }
    
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取面试详情失败')
  } finally {
    loadingDetail.value = false
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    
    // 合并日期和时间
    let interviewTime = null
    if (form.interviewDate && form.interviewTime) {
      try {
        // 确保时间格式为 HH:mm
        const timeStr = typeof form.interviewTime === 'string' ? form.interviewTime : 
                       `${String(form.interviewTime.getHours()).padStart(2, '0')}:${String(form.interviewTime.getMinutes()).padStart(2, '0')}`
        
        // 格式化日期为 YYYY-MM-DD
        const date = new Date(form.interviewDate)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        
        // 组合成后端需要的格式：YYYY-MM-DD HH:mm:ss
        interviewTime = `${year}-${month}-${day} ${timeStr}:00`
      } catch (e) {
        console.error('合并时间失败:', e)
        ElMessage.error('时间格式错误')
        return
      }
    }
    
    // 构建提交数据
    const submitData = {
      ...form,
      interviewTime,
      // 确保所有数字字段都是有效的数字
      interviewType: Number(form.interviewType) || 1,
      sendEmail: Number(form.sendEmail) || 0,
      duration: Number(form.duration) || 60,
      candidateId: Number(form.candidateId),
      positionId: Number(form.positionId),
      digitalInterviewerId: form.digitalInterviewerId ? Number(form.digitalInterviewerId) : null,
      questionSetIds: Array.isArray(form.questionSetIds) ? form.questionSetIds.map(id => Number(id)) : [],
      // 添加更新时间
      updatedAt: new Date().toISOString().slice(0, 19).replace('T', ' ')
    }
    
    // 删除不需要的字段
    delete submitData.interviewDate
    delete submitData.status
    
    console.log('提交的数据:', submitData)
    
    let res
    if (form.id) {
      // 更新
      res = await updateSchedule(submitData)
    } else {
      // 新增
      res = await addSchedule(submitData)
    }
    
    if (res.code === 200) {
      ElMessage.success(form.id ? '更新成功' : '添加成功')
      dialogVisible.value = false
      fetchSchedules()
    } else {
      ElMessage.error(res.msg || (form.id ? '更新失败' : '添加失败'))
    }
  } catch (error) {
    console.error('提交表单错误:', error)
    ElMessage.error('提交表单错误: ' + error.message)
  }
}

// 删除记录
const cancelInterview = async (id) => {
  try {
    await ElMessageBox.confirm('确定要取消该面试吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteSchedule(id)
    if (response.code === 200) {
      ElMessage.success('面试已取消')
      fetchSchedules()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消面试失败')
    }
  }
}

// 页面变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchSchedules()
}

// 对话框关闭前的回调
const handleClose = (done) => {
  ElMessageBox.confirm('确认关闭？')
    .then(() => {
      done()
    })
    .catch(() => {})
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  try {
    const d = new Date(date)
    if (isNaN(d.getTime())) return ''
    return d.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    }).replace(/\//g, '-')
  } catch (e) {
    console.error('格式化日期失败:', e)
    return ''
  }
}

// 格式化时间
const formatTime = (datetime) => {
  if (!datetime) return ''
  try {
    const d = new Date(datetime)
    if (isNaN(d.getTime())) return ''
    return d.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (e) {
    console.error('格式化时间失败:', e)
    return ''
  }
}

// 获取候选人名称
const getCandidateName = (candidateId) => {
  if (!candidateId) return '未知'
  if (!Array.isArray(candidates.value)) {
    return '未知'
  }
  
  const candidate = candidates.value.find(c => {
    // 尝试多种可能的ID字段
    const possibleIds = [
      c.id,
      c.candidateId,
      c.candidate_id,
      c.candidateId
    ].filter(id => id !== undefined)
    
    return possibleIds.some(id => String(id) === String(candidateId))
  })
  
  return candidate ? candidate.name : '未知'
}

// 获取职位名称
const getPositionName = (id) => {
  if (!id) return '未知'
  if (!Array.isArray(positions.value)) {
    return '未知'
  }
  const position = positions.value.find(p => {
    const positionId = String(p.id || p.positionId)
    const searchId = String(id)
    return positionId === searchId
  })
  return position ? (position.name || position.positionName) : '未知'
}

// 获取面试官名称
const getInterviewerName = (id) => {
  if (!id) return '未知'
  if (!Array.isArray(interviewers.value)) {
    return '未知'
  }
  const interviewer = interviewers.value.find(i => {
    const interviewerId = String(i.id || i.interviewerId)
    const searchId = String(id)
    return interviewerId === searchId
  })
  return interviewer ? (interviewer.name || interviewer.interviewerName) : '未知'
}

// 获取题目集名称
const getQuestionSetNames = (ids) => {
  if (!ids || !Array.isArray(ids)) {
    return '未设置'
  }
  
  const names = ids.map(id => {
    const set = questionSets.value.find(q => String(q.id) === String(id))
    return set ? set.name : '未知'
  })
  
  return names.length > 0 ? names.join('、') : '未设置'
}

// 获取题目集详情
const getQuestionSetDetails = (ids) => {
  if (!ids || !Array.isArray(ids)) {
    return []
  }
  
  return ids.map(id => {
    const set = questionSets.value.find(q => String(q.id) === String(id))
    return set || { id, name: '未知题目集' }
  })
}

// 页面加载时获取数据
onMounted(async () => {
  try {
    // 先获取基础数据
    await fetchOptions()
    // 再获取表格数据
    await fetchSchedules()
  } catch (error) {
    ElMessage.error('初始化数据失败')
  }
})
</script>

<style scoped>
.app-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.content-wrapper {
  flex: 1;
  width: 100%;
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
}

.schedule-table-wrapper {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

:deep(.el-table) {
  flex: 1;
  width: 100% !important;
}

:deep(.el-table__inner-wrapper) {
  height: 100%;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.header-left h1 {
  font-size: 28px;
  font-weight: 600;
  margin: 0;
  margin-bottom: 8px;
  color: #1f2f3d;
}

.header-left p {
  color: #606266;
  margin: 0;
  font-size: 16px;
}

.header-right {
  padding-top: 8px;
}

.add-btn {
  padding: 12px 24px;
  font-size: 16px;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.candidate-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-weight: 600;
  font-size: 16px;
}

.candidate-name {
  font-size: 16px;
  font-weight: 600;
  color: #1f2f3d;
}

.interviewer-info,
.date-info,
.time-info,
.duration-info,
.location-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

.status-tag {
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 14px;
}

.operation-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 16px;
  white-space: nowrap;
  min-width: 240px;
}

.action-btn {
  padding: 4px 12px;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  height: 28px;
  min-width: 70px;
}

.action-btn .el-icon {
  font-size: 16px;
  margin-right: 4px;
}

.pagination-container {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 24px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: 600;
  color: #1f2f3d;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
}

.schedule-form {
  padding: 0 20px;
}

.schedule-form :deep(.el-form-item) {
  margin-bottom: 24px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 面试详情样式 */
.schedule-detail {
  padding: 20px;
}

.detail-section {
  margin-bottom: 32px;
}

.detail-section h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1f2f3d;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-descriptions__label) {
  width: 120px;
  font-weight: 500;
}

.remarks-content {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

@media screen and (max-width: 1400px) {
  .content-wrapper {
    max-width: 100%;
    margin: 0;
  }
}

@media screen and (max-width: 768px) {
  .app-container {
    padding: 16px;
  }

  .schedule-table-wrapper {
    padding: 16px;
  }

  .table-header {
    flex-direction: column;
    gap: 16px;
    margin-bottom: 16px;
  }
}

:deep(.el-table .operation-column .cell) {
  padding: 0 16px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
}

.question-set-info,
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

.question-set-info .el-icon,
.user-info .el-icon {
  font-size: 16px;
  color: #909399;
}

:deep(.el-table .question-set-column) {
  min-width: 150px;
  width: 15%;
}

:deep(.el-table .created-by-column) {
  min-width: 120px;
  width: 12%;
}

:deep(.el-table .create-time-column) {
  min-width: 160px;
  width: 16%;
}

:deep(.el-table .update-time-column) {
  min-width: 160px;
  width: 16%;
}
</style> 